package models

import (
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

//DateManufacture int64  //生产日期
//BatchNumbers    string //批号
//EffectiveDate   int64  //有效日期
type ErpInventory struct {
	Id                   int64
	DepartmentId         int64
	ProductName          string //产品名称
	Products             *ErpProducts       `orm:"rel(fk);null;on_delete(do_nothing)"`
	Acceptance           *ErpAcceptanceData `orm:"rel(fk);null;on_delete(do_nothing)"` //验收ID
	Snd                  *ErpProductsSnd    `orm:"rel(fk);null;on_delete(do_nothing)"`
	Diopter              string             `json:"sph" orm:"-"` //球镜
	Astigmatism          string             `json:"cyl" orm:"-"` //柱镜
	Addlight             string             `json:"add" orm:"-"` //下加光
	SalesVolume          int64              `json:"sales_volume"`
	ColourNumber         string             `orm:"-"`
	ModelNumber          string             `orm:"-"`
	Size                 string             `orm:"-"`             //尺寸
	FunctionInfo         string             `orm:"-"`             //功效
	FilmColor            string             `orm:"-"`             //膜层颜色
	Genre                string             `orm:"-"`             //框型
	Inventory            int64              `json:"purchase_num"` //
	UpdatedAt            int64
	UpdatedBy            string
	Hascode              string
	SuggestedPrice       float64 `orm:"-" json:"suggested_price"`
	TradePrice           float64 `orm:"-" json:"trade_price"`
	CustomSuggestedPrice float64 `orm:"-" json:"custom_suggested_price"`
	CustomTradePrice     float64 `orm:"-" json:"custom_trade_price"`
	PriceId              int64   `orm:"-" json:"price_id"`
}

//查询
type ErpInventoryQueryParam struct {
	BaseQueryParam
	Filter           string `json:"pname"`              //名称查询
	OrFilter         string `json:"orFilter"`           //or查询
	Products         int64  `json:"products_id"`        //产品Id
	Typeid           int    `json:"typeid"`             //类别ID
	Typeids          []int  `json:"typeids"`            //类别ID
	MaterialQuality  string `json:"material_quality"`   //材质
	Isnegative       string `json:"isnegative"`         //包含负库存
	Refractivity     string `json:"refractivity"`       //折射率
	OpticalDesign    string `json:"optical_design"`     //光学设计
	FunctionInfo     string `json:"function_info"`      //功效
	Genre            string `json:"genre"`              //类型
	Film             string `json:"film"`               //膜层
	QueryDr          string `json:"query_dr"`           //屈光度
	QueryAm          string `json:"query_am"`           //散光度
	CastAway         string `json:"cast_away"`          //配戴周期
	Addlight         string `json:"addlight"`           //下加光
	Addlight1        string `json:"addlight_1"`         //下加光1
	QueryDr1         string `json:"query_dr_1"`         //屈光度1
	QueryAm1         string `json:"query_am_1"`         //散光度1
	BrandId          int64  `json:"brand_id"`           //品牌
	BrandName        string `json:"brand_name"`         //品牌名称
	ModelNumber      string `json:"model_number"`       //型号
	ColourNumber     string `json:"colour_number"`      //色号
	Size             string `json:"size"`               //尺寸
	Spec             string `json:"spec"`               //规格
	CareSolutionSpec string `json:"care_solution_spec"` //护理产品规格
	Hascode          string                             //哈希查询
	Department       int64                              //部门
	ExtendDepartment []interface{}                      //扩展部门查询
	Suppliers        int64 `json:"suppliers"`           //供应商
	NeedPrice        bool                               //是否需要输出价格
}

func (a *ErpInventory) TableName() string {
	return ErpInventoryTableName()
}

func ErpInventoryTableName() string {
	return TableName("erp_inventory")
}

/**
* 增计算哈希值
* PID产品ID-DEP部门ID-ET验收ID-DR屈光度-AM散光度-MN型号-CN色号-SI尺寸-FI功效-FC膜层颜色-GE框型
 */
func CalculateInventoryHascode(d *ErpInventory) (string, error) {
	//生成哈希值，产品ID-部门ID-屈光度-散光度-生产编号-供应商ID
	if d.Products.Id == 0 {
		return "", errors.New("产品不能为空")
	}
	if d.DepartmentId == 0 {
		return "", errors.New("部门不能为空")
	}
	hasData := []byte(fmt.Sprintf("%d-%d-%d-%d", d.Products.Id, d.DepartmentId, d.Acceptance.Id, d.Snd.Id))
	has := md5.Sum(hasData)
	return fmt.Sprintf("%x", has), nil
}

func erpInventoryPageListQuerySeter(params *ErpInventoryQueryParam) orm.QuerySeter {

	query := orm.NewOrm().QueryTable(ErpInventoryTableName()).RelatedSel("Products", "Products__Suppliers", "Acceptance", "Snd")

	cond := orm.NewCondition()

	if params.Department > 0 { //按部门查询
		cond = cond.And("department_id", params.Department)
	}
	if len(params.Filter) > 0 { //搜索直接查规格名
		condnn := orm.NewCondition()
		condnb := condnn.Or("Products__BrandName__contains", params.Filter).Or("Products__Name__contains", params.Filter).Or("Products__pinyin__contains", params.Filter).Or("product_name__contains", params.Filter)
		cond = cond.AndCond(condnb)
	}

	if len(params.BrandName) > 0 { //品牌名称搜索
		cond = cond.And("Products__BrandName__contains", params.BrandName)
	}
	if len(params.Refractivity) > 0 { //折射率
		cond = cond.And("Products__Refractivity", params.Refractivity)
	}
	if len(params.OpticalDesign) > 0 { //光学设计
		cond = cond.And("Products__OpticalDesign", params.OpticalDesign)
	}
	if len(params.CastAway) > 0 { //配戴周期
		cond = cond.And("Products__CastAway", params.CastAway)
	}
	if len(params.Genre) > 0 { //镜片类型
		cond = cond.And("Products__Genre", params.Genre)
	}
	if len(params.Spec) > 0 { //隐形规格
		cond = cond.And("Products__Spec", params.Spec)
	}
	if len(params.CareSolutionSpec) > 0 { //护理产品规格
		cond = cond.And("Products__Spec", params.CareSolutionSpec)
	}

	switch params.Typeid {
	case 10:
		if len(params.Film) > 0 { //膜层
			cond = cond.And("Products__Film", params.Film)
		}
		if len(params.FunctionInfo) > 0 { //功效
			cond = cond.And("Products__FunctionInfo", params.FunctionInfo)
		}
	case 41:
		if len(params.FunctionInfo) > 0 { //功效
			cond = cond.And("Snd__FunctionInfo", params.FunctionInfo)
		}
	}

	if params.Products > 0 {
		cond = cond.And("Products__Id__eq", params.Products)
	}

	if params.Typeid > 0 {
		cond = cond.And("Products__TypeId__eq", params.Typeid)
	}
	if len(params.Typeids) > 0 {
		cond = cond.And("Products__TypeId__in", params.Typeids)
	}

	if params.BrandId > 0 {
		cond = cond.And("Products__Brand__Id__eq", params.BrandId)
	}

	if len(params.ModelNumber) > 0 { //型号
		cond = cond.And("Snd__Model", params.ModelNumber)
	}
	if params.Typeid == 20 {
		if len(params.ColourNumber) > 0 { //色号
			cond = cond.And("Products__ColourNumber", params.ColourNumber)
		}
	} else {
		if len(params.ColourNumber) > 0 { //色号
			cond = cond.And("Snd__Color", params.ColourNumber)
		}
	}
	if len(params.Size) > 0 { //尺寸
		cond = cond.And("Snd__Size", params.Size)
	}

	if len(params.Isnegative) > 0 && params.Isnegative == "1" { //库存有货
		cond = cond.And("inventory__gt", 0)
	}
	if len(params.Isnegative) > 0 && params.Isnegative == "2" { //库存无货
		cond = cond.And("inventory__lte", 0)
	}

	if params.Suppliers > 0 {
		cond = cond.And("Products__Suppliers__Id", params.Suppliers)
	}

	conds := orm.NewCondition()

	if len(params.QueryDr) > 0 && len(params.QueryDr1) > 0 {
		cond1 := conds.Or("Snd__Sph", params.QueryDr).Or("Snd__Sph", params.QueryDr1)
		cond = cond.AndCond(cond1)
	} else if len(params.QueryDr) > 0 {
		cond = cond.And("Snd__Sph", params.QueryDr)
	} else if len(params.QueryDr1) > 0 {
		cond = cond.And("Snd__Sph", params.QueryDr1)
	}

	if len(params.QueryAm) > 0 && len(params.QueryAm1) > 0 {
		cond1 := conds.Or("Snd__Cyl", params.QueryAm).Or("Snd__Cyl", params.QueryAm1)
		cond = cond.AndCond(cond1)
	} else if len(params.QueryAm) > 0 {
		cond = cond.And("Snd__Cyl", params.QueryAm)
	} else if len(params.QueryAm1) > 0 {
		cond = cond.And("Snd__Cyl", params.QueryAm1)
	}

	if len(params.Addlight) > 0 && len(params.Addlight1) > 0 {
		cond1 := conds.Or("Snd__Add", params.Addlight).Or("Snd__Add", params.Addlight1)
		cond = cond.AndCond(cond1)
	} else if len(params.Addlight) > 0 {
		cond = cond.And("Snd__Add", params.Addlight)
	} else if len(params.Addlight1) > 0 {
		cond = cond.And("Snd__Add", params.Addlight1)
	}
	if len(params.OrFilter) > 0 {
		condss := orm.NewCondition()
		cond2 := condss.Or("Snd__Model__icontains", params.OrFilter).Or("Snd__Color__icontains", params.OrFilter).Or("product_name__icontains", params.OrFilter)
		cond = cond.AndCond(cond2)
	}

	query = query.SetCond(cond)

	return query
}

func ErpInventoryPageList(params *ErpInventoryQueryParam) ([]*ErpInventory, int64) {

	ls := make([]*ErpInventory, 0)

	query := erpInventoryPageListQuerySeter(params)

	total, _ := query.Count()

	sortorder := "-Id"
	switch params.Sort {
	case "Id":
		sortorder = "Id"
	case "expiry_date":
		sortorder = "Acceptance__expiry_date"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func ErpInventoryList(params *ErpInventoryQueryParam) []*ErpInventory {

	ls := make([]*ErpInventory, 0)
	query := erpInventoryPageListQuerySeter(params)
	query.OrderBy("-Id").Limit(-1).All(&ls)

	return ls
}

//获取单条数据
func ErpInventoryFind(id int64) *ErpInventory {
	model := new(ErpInventory)
	orm.NewOrm().QueryTable(ErpInventoryTableName()).RelatedSel("Products", "Snd").Filter("id", id).One(model)
	return model
}

//按SND数据获取库存信息
func GetSndForInventoryPageList(params *ErpInventoryQueryParam) ([]*ErpInventory, int64) {

	ls := make([]*ErpInventory, 0)
	query := orm.NewOrm().QueryTable(ErpProductsSndTableName()).RelatedSel("Products")
	cond := orm.NewCondition()

	if len(params.ExtendDepartment) > 0 {
		cond = cond.And("Products__DepartmentId__in", params.ExtendDepartment)
	}
	if params.Products > 0 {
		cond = cond.And("Products__Id", params.Products)
	}
	if params.Typeid > 0 {
		cond = cond.And("Products__TypeId__eq", params.Typeid)
	}
	if len(params.Typeids) > 0 {
		cond = cond.And("Products__TypeId__in", params.Typeids)
	}

	if len(params.Filter) > 0 { //搜索直接查规格名
		cond = cond.And("Products__Name__contains", params.Filter)
	}

	if len(params.BrandName) > 0 { //品牌名称搜索
		cond = cond.And("Products__BrandName__contains", params.BrandName)
	}
	if len(params.Refractivity) > 0 { //折射率
		cond = cond.And("Products__Refractivity", params.Refractivity)
	}
	if len(params.OpticalDesign) > 0 { //光学设计
		cond = cond.And("Products__OpticalDesign", params.OpticalDesign)
	}
	if len(params.MaterialQuality) > 0 { //光学设计
		cond = cond.And("Products__MaterialQuality", params.MaterialQuality)
	}
	switch params.Typeid {
	case 10:
		if len(params.Film) > 0 { //膜层
			cond = cond.And("Products__Film", params.Film)
		}
		if len(params.FunctionInfo) > 0 { //功效
			cond = cond.And("Products__FunctionInfo", params.FunctionInfo)
		}
	case 41:
		if len(params.FunctionInfo) > 0 { //功效
			cond = cond.And("FunctionInfo", params.FunctionInfo)
		}
	}

	if params.Typeid == 20 {
		if len(params.ColourNumber) > 0 { //色号
			cond = cond.And("Products__ColourNumber", params.ColourNumber)
		}
	} else {
		if len(params.ColourNumber) > 0 { //色号
			cond = cond.And("Color", params.ColourNumber)
		}
	}
	if len(params.ModelNumber) > 0 { //型号
		cond = cond.And("Model", params.ModelNumber)
	}
	if len(params.Size) > 0 { //尺寸
		cond = cond.And("Size", params.Size)
	}
	//查询球柱镜
	conds := orm.NewCondition()
	if len(params.QueryDr) > 0 && len(params.QueryDr1) > 0 {
		cond1 := conds.Or("Sph", params.QueryDr).Or("Sph", params.QueryDr1)
		cond = cond.AndCond(cond1)
	} else if len(params.QueryDr) > 0 {
		cond = cond.And("Sph", params.QueryDr)
	} else if len(params.QueryDr1) > 0 {
		cond = cond.And("Sph", params.QueryDr1)
	}

	if len(params.QueryAm) > 0 && len(params.QueryAm1) > 0 {
		cond1 := conds.Or("Cyl", params.QueryAm).Or("Cyl", params.QueryAm1)
		cond = cond.AndCond(cond1)
	} else if len(params.QueryAm) > 0 {
		cond = cond.And("Cyl", params.QueryAm)
	} else if len(params.QueryAm1) > 0 {
		cond = cond.And("Cyl", params.QueryAm1)
	}

	if len(params.Addlight) > 0 && len(params.Addlight1) > 0 {
		cond1 := conds.Or("Add", params.Addlight).Or("Add", params.Addlight1)
		cond = cond.AndCond(cond1)
	} else if len(params.Addlight) > 0 {
		cond = cond.And("Add", params.Addlight)
	} else if len(params.Addlight1) > 0 {
		cond = cond.And("Add", params.Addlight1)
	}

	query = query.SetCond(cond)
	sortorder := "-Id"
	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	total, _ := query.Count()

	sndls := make([]*ErpProductsSnd, 0)
	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&sndls)

	return ls, total
}
